<template>
  <div class="chat-management-container">
    <!-- 标题区 -->
    <div class="header-section">
      <h2 class="management-title">
        <el-icon class="title-icon">
          <ChatLineRound />
        </el-icon>
        聊天记录管理
      </h2>
      <el-divider class="title-divider" />
    </div>

    <!-- 智能搜索卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form ref="searchForm" :model="queryParams" class="smart-search-form">
        <el-row :gutter="20">
          <!-- 发送者搜索 -->
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="发送者" prop="sender">
              <el-input v-model="queryParams.sender" placeholder="用户ID/昵称" clearable suffix-icon="User"
                @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>

          <!-- 接收者搜索 -->
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="接收者" prop="receiver">
              <el-input v-model="queryParams.receiver" placeholder="用户ID/昵称" clearable suffix-icon="User"
                @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>

          <!-- 内容搜索 -->
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="消息内容" prop="content">
              <el-input v-model="queryParams.content" placeholder="文本/文件路径" clearable suffix-icon="Search"
                @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>

          <!-- 时间范围 -->
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="时间范围" prop="dateRange">
              <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="—"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" :shortcuts="dateShortcuts"
                class="full-width-datepicker" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="data-card" shadow="hover">
      <el-table :data="messages" v-loading="loading" border stripe highlight-current-row height="calc(100vh - 320px)"
        :default-sort="{ prop: 'timestamp', order: 'descending' }">
        <!-- 发送者列 -->
        <el-table-column prop="sender" label="发送者" width="120" fixed="left" />

        <!-- 接收者列 -->
        <el-table-column prop="receiver" label="接收者" width="120" fixed="left" />


        <!-- 内容列（最终优化版） -->
        <el-table-column label="内容" min-width="300">
          <template #default="{ row }">
            <div class="media-content">
              <!-- 主要根据mediaType判断 -->
              <template v-if="row.mediaType === 'image' || isImage(row.content)">
                <el-image :src="getImageUrl(row.content)" :preview-src-list="[getImageUrl(row.content)]" fit="cover"
                  class="media-image" hide-on-click-modal>
                  <template #error>
                    <div class="image-error">
                      <el-icon>
                        <Picture />
                      </el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </template>

              <template v-else-if="row.mediaType === 'video' || isVideo(row.content)">
                <video controls :src="getVideoUrl(row.content)" class="media-video" />
              </template>

              <!-- 默认显示文本 -->
              <template v-else>
                <div class="text-bubble">{{ row.content }}</div>
              </template>
            </div>
          </template>
        </el-table-column>

        <!-- 类型列 -->
        <el-table-column label="类型" width="110">
          <template #default="{ row }">
            <el-tag :type="mediaTypeTag(row.mediaType)" effect="plain">
              {{ mediaTypeText(row.mediaType) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 时间列 -->
        <el-table-column prop="timestamp" label="时间" sortable width="160" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" :icon="Delete" circle @click="handleDelete(row.id)"
              :loading="deleteLoading[row.id]" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="smart-pagination">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" @current-change="handlePageChange"
          @size-change="handleSizeChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ChatLineRound,
  Delete,
  Picture,
  Search,
  Refresh,
  User 
} from '@element-plus/icons-vue'

const RESOURCE_BASE = 'http://localhost:8081'

// 响应式数据
const queryParams = ref({
  sender: '',
  receiver: '',
  content: '',
  dateRange: []
})

const messages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const deleteLoading = ref({})

// 日期快捷选项
const dateShortcuts = [
  { text: '今天', value: () => [dayjs().toDate(), dayjs().toDate()] },
  { 
    text: '最近一周', 
    value: () => [dayjs().subtract(7, 'day').toDate(), dayjs().toDate()] 
  },
  { 
    text: '本月', 
    value: () => [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()]
  }
]

// 获取数据
const fetchChatList = async () => {
  try {
    loading.value = true
    const params = {
    page: currentPage.value,
    size: pageSize.value,
    sender: queryParams.value.sender || null, // 传递null而不是空字符串
    receiver: queryParams.value.receiver || null,
    content: queryParams.value.content || null,
    startDate: queryParams.value.dateRange?.[0] || null, // 传递日期参数
    endDate: queryParams.value.dateRange?.[1] || null
  }

    const { data } = await axios.get(`${RESOURCE_BASE}/chat/list`, { 
      params,
      timeout: 10000
    })
    console.log('fetchChatList', params)
    console.log(data)

    if (data.code === 200) {
      messages.value = data.data.map(item => ({
  ...item,
  // 确保mediaType转换正确
  mediaType: (item.media_type || 'text').toLowerCase(),
  timestamp: dayjs(item.timestamp).format('YYYY-MM-DD HH:mm')
}))
      total.value = data.total
    }
  } catch (error) {
    handleApiError(error, '加载失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchChatList()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = { sender: '', receiver: '', content: '', dateRange: [] }
  handleSearch()
}

// 删除处理
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定永久删除该记录？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    deleteLoading.value[id] = true
    const { data } = await axios.delete(`${RESOURCE_BASE}/chat/delete/${id}`)

    if (data.code === 200) {
      ElMessage.success('删除成功')
      messages.value = messages.value.filter(msg => msg.id !== id)
      total.value = Math.max(total.value - 1, 0)
    }
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error, '删除失败')
    }
  } finally {
    deleteLoading.value[id] = false
  }
}

// 分页处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchChatList()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  handleSearch()
}

// 工具函数
const isImage = (url) => /\.(jpg|jpeg|png|webp|gif)$/i.test(url)
const isVideo = (url) => /\.(mp4|mov|avi|webm)$/i.test(url)
const getImageUrl = (path) => `${RESOURCE_BASE}/avatars/${encodeURIComponent(path)}`
const getVideoUrl = (path) => `${RESOURCE_BASE}/video/${encodeURIComponent(path)}`

// 工具函数改为从mediaType判断
const mediaTypeTag = (type) => ({
  text: '',
  image: 'success',
  video: 'warning'
}[type?.toLowerCase()])  // 增加容错处理

const mediaTypeText = (type) => ({
  text: '文本',
  image: '图片',
  video: '视频'
}[type?.toLowerCase()])  // 增加容错处理

const handleApiError = (error, defaultMsg) => {
  const msg = error.response?.data?.message || error.message || defaultMsg
  ElMessage.error(msg)
  console.error('API Error:', error)
}

// 初始化加载
onMounted(fetchChatList)
</script>

<style lang="scss" scoped>
.chat-management-container {
  padding: 20px;
  background: #f8fafc;
}

.header-section {
  margin-bottom: 25px;

  .management-title {
    display: flex;
    align-items: center;
    font-size: 20px;
    color: #2c3e50;
    font-weight: 600;

    .title-icon {
      margin-right: 10px;
      font-size: 24px;
      color: #409eff;
    }
  }

  .title-divider {
    margin: 10px 0;
    border-color: #e4e7ed;
  }
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background: #ffffff;

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.smart-search-form {
  .el-form-item {
    margin-bottom: 18px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }
  }

  .full-width-datepicker {
    width: 100%;
  }

  .form-actions {
    margin-top: 10px;
    text-align: right;

    .el-button {
      padding: 9px 20px;
      border-radius: 4px;
      transition: all 0.3s;

      + .el-button {
        margin-left: 10px;
      }
    }
  }
}

.data-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background: #ffffff;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.media-content {
  padding: 8px 0;

  .text-bubble {
    display: inline-block;
    padding: 8px 12px;
    background: #f0f4ff;
    border-radius: 6px;
    line-height: 1.5;
    color: #303133;
  }

  .media-image {
    max-width: 150px;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 0.2s;

    &:hover {
      transform: scale(1.03);
    }
  }

  .media-video {
    max-width: 250px;
    border-radius: 4px;
    background: #000;
  }
}

.image-error {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #fef0f0;
  border-radius: 4px;
  color: #f56c6c;

  .el-icon {
    margin-right: 5px;
  }
}

.smart-pagination {
  padding: 16px;
  border-top: 1px solid #ebeef5;

  :deep(.el-pagination) {
    justify-content: flex-end;
  }
}
</style>